package com.tybbank.Activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.liji.imagezoom.util.ImageZoom;
import com.nanchen.compresshelper.CompressHelper;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.IntoBean;
import com.tybbank.Bean.YZMBean;
import com.tybbank.Login.LoginActivity;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.ActivityUtil;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.Utils.StatusBarUtil;
import com.tybbank.Utils.logUtilssss;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/11/27 0027.
 */

public class BuyGoldActivity extends BaseActivity {

    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.et_pay_pwdnum)
    EditText etPayPwdnum;
    @BindView(R.id.wuyong1)
    TextView wuyong1;
    @BindView(R.id.iv_add_with_hand)
    ImageView ivAddWithHand;
    @BindView(R.id.bt_enter)
    Button btEnter;
    @BindView(R.id.tv_look_erweima)
    TextView tvLookErweima;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_veizhu)
    TextView tvVeizhu;
    @BindView(R.id.et_id_dizhi)
    EditText etIdDizhi;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.ib_exit)
    ImageButton ibExit;
    @BindView(R.id.tv_chongbi)
    TextView tvChongbi;
    @BindView(R.id.line_chongbi)
    View lineChongbi;
    @BindView(R.id.rl_chongbi)
    RelativeLayout rlChongbi;
    @BindView(R.id.tv_jinbiwang)
    TextView tvJinbiwang;
    @BindView(R.id.line_jinbiwang)
    View lineJinbiwang;
    @BindView(R.id.rl_jinbiwang)
    RelativeLayout rlJinbiwang;
    @BindView(R.id.tv_jilu)
    TextView tvJilu;
    private File file;//图片
    private String imageUrl = "";
    private String recharge_money_path;
    private String money_path;
    private int TAG = 2;// 1是金币网  2 是乾坤网

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_gold);
        ButterKnife.bind(this);
        TAG = 2;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            StatusBarUtil.setStatusBarColor(BuyGoldActivity.this, R.color.backgroundcolorhei723);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.GONE);
        }

        initdata();
    }


    private void initdata() {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("token", MyApplication.token);
        parameters.put("TimeStamp", time);
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(this, getString(R.string.loading));
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.recharge_config)
                .addParams("uuid", MyApplication.uuid)
                .addParams("token", MyApplication.token)
                .addParams("TimeStamp", time)
                .addParams("Sign", sign)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        showTips(getString(R.string.error));
                        return;
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG充值页面配置信息" + response.toString());
                        dialog.dismiss();
                        string(response);
                    }

                    private void string(String json) {
                        IntoBean enterBean = new Gson().fromJson(json, new TypeToken<IntoBean>() {
                        }.getType());
                     String   fanhuistring= "";
                        int status = enterBean.getCode();
                        if (status == 1011) {
                            if (TAG ==1){
                                List<String> info = enterBean.getJinbi().getInfo();
                                for (int i = info.size() -1; i>= 0; i--) {
                                    fanhuistring = "     "+(i+1)+": "+info.get(i) + "\n" + fanhuistring;
                                }
                                tvVeizhu.setText("说明:\n" + fanhuistring);
                                recharge_money_path = enterBean.getJinbi().getMoney_path();
                                tvAddress.setText(recharge_money_path);
                                money_path = enterBean.getJinbi().getQrcord();
                            }else if (TAG==2){
                            List<String> info = enterBean.getQiankun().getInfo();
                            for (int i = info.size() -1; i>= 0; i--) {
                                fanhuistring = "     "+(i+1)+": "+info.get(i) + "\n" + fanhuistring;
                            }
                            tvVeizhu.setText("说明:\n" + fanhuistring);
                                recharge_money_path = enterBean.getQiankun().getMoney_path();
                                tvAddress.setText(recharge_money_path);
                                money_path = enterBean.getJinbi().getQrcord();
                            }
                        } else if (status == 1004) {
                            Intent intent = new Intent(getBaseContext(), LoginActivity.class);
                            startActivity(intent);
                            return;
                        } else {
                            showTips(enterBean.getMsg());
                        }
                    }
                });
    }

    @SuppressLint("WrongConstant")
    @OnClick({R.id.rl_chongbi, R.id.rl_jinbiwang, R.id.tv_jilu, R.id.ib_exit, R.id.iv_add_with_hand, R.id.bt_enter, R.id.tv_look_erweima})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ib_exit:
                BuyGoldActivity.this.finish();
                break;
            case R.id.rl_chongbi:// 冲币按钮
                TAG = 1;
                initdata();
                tvChongbi.setTextColor(getResources().getColor(R.color.textcolormain));
                lineChongbi.setBackgroundColor(getResources().getColor(R.color.textcolormain));
                tvJinbiwang.setTextColor(getResources().getColor(R.color.textcolorbai));
                lineJinbiwang.setBackgroundColor(getResources().getColor(R.color.textcolorbai));
                break;
            case R.id.rl_jinbiwang: // 金币网按钮
                TAG = 2;
                initdata();
                tvJinbiwang.setTextColor(getResources().getColor(R.color.textcolormain));
                lineJinbiwang.setBackgroundColor(getResources().getColor(R.color.textcolormain));
                tvChongbi.setTextColor(getResources().getColor(R.color.textcolorbai));
                lineChongbi.setBackgroundColor(getResources().getColor(R.color.textcolorbai));
                break;

            case R.id.tv_jilu:  //记录
                    Intent intent = new Intent(this, BuySellListActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                break;
            case R.id.tv_look_erweima:
                if (!TextUtils.isEmpty(money_path)) {
                    ImageZoom.show(this, money_path);
                } else {
                    showTips(getString(R.string.error));
                }
                break;
            case R.id.iv_add_with_hand:
                selectPhoto();
                break;
            case R.id.bt_enter:
                if (TextUtils.isEmpty(etIdDizhi.getText().toString().trim())) {
                    logUtilssss.toast(this, getString(R.string.jiaoyiidhit));
                    return;
                } else if (TextUtils.isEmpty(etNum.getText().toString().trim())) {
                    logUtilssss.toast(this, getString(R.string.hintnum));
                    return;
                } else if (TextUtils.isEmpty(etPayPwdnum.getText().toString().trim())) {
                    logUtilssss.toast(this, getString(R.string.paypwdhint));
                    return;
                } else if (TextUtils.isEmpty(imageUrl)) {
                    Toast.makeText(getBaseContext(), getString(R.string.pingzheng),Toast.LENGTH_SHORT).show();
                    return;
                } else {

                    if (TAG ==1){
                        initview("1");
                    }else   if (TAG ==2){
                        initview("2");
                    }
                }
                break;
        }
    }

    private void initview(String  str) {
        String time = MD5Utils.getTime();
        SortedMap<String, String> parameters = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj1.compareTo(obj2);
                    }
                });
        parameters.put("uuid", MyApplication.uuid);
        parameters.put("pay_pwd", MD5Utils.md5Password(etPayPwdnum.getText().toString().trim()));
        parameters.put("number", etNum.getText().toString().trim());
        parameters.put("trade", etIdDizhi.getText().toString().trim());
        parameters.put("img_path", MyApplication.imageurltwo);
        parameters.put("token", MyApplication.token);
        parameters.put("TimeStamp", time);
        parameters.put("type", str);
        String sign = MD5Utils.createSign(parameters);
        final Dialog dialog = MyDialogUtils.createLoadingDialog(this, "正在加载...");
        dialog.show();
        OkHttpUtils.post()
                .url(Constant.abc_recharge)
                .addParams("uuid", MyApplication.uuid)
                .addParams("img_path", MyApplication.imageurltwo)
                .addParams("token", MyApplication.token)
                .addParams("pay_pwd", MD5Utils.md5Password(etPayPwdnum.getText().toString().trim()))
                .addParams("TimeStamp", time)
                .addParams("number", etNum.getText().toString().trim())
                .addParams("trade", etIdDizhi.getText().toString().trim())
                .addParams("Sign", sign)
                .addParams("type", str)
                .build()
                .readTimeOut(30000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG上传图片结果" + response);
                        dialog.dismiss();
                        YZMBean result = new Gson().fromJson(response, YZMBean.class);

                        if (result.getCode() == 1011) {
                            showTips(result.getMsg());
                            setResult(RESULT_OK);
                            BuyGoldActivity.this.finish();
                        } else if (result.getCode() == 1004) {
                            Intent intent = new Intent(BuyGoldActivity.this, LoginActivity.class);
                            startActivity(intent);
                            return;
                        } else {
                            showTips(result.getMsg());
                        }
                    }
                });
    }

    //选择图片
    private void selectPhoto() {
        // 自定义图片加载器
        ImageLoader loader = new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                // TODO 在这边可以自定义图片加载库来加载ImageView，例如Glide、Picasso、ImageLoader等
                Glide.with(context).load(path).into(imageView);
            }


        };
        // 自由配置选项
        ImgSelConfig config = new ImgSelConfig.Builder(this, loader)
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(R.mipmap.icon_close)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#3F51B5"))
                // 裁剪大小。needCrop为true的时候配置
//                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(true)
                // 最大选择图片数量，默认9
                .maxNum(1).build();
        // 跳转到图片选择器
        ImgSelActivity.startActivity(this, config, Constant.HEAD_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 图片选择结果回调
        if (requestCode == Constant.HEAD_IMAGE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
//            file = new File(pathList.get(0));//写死只获取第一张图片
            //新的功能，上传前压缩图片 2018.05.29版本5

            file = CompressHelper.getDefault(this).compressToFile(new File(pathList.get(0)));
            imageUrl = pathList.get(0);
            logUtilssss.e("拍完照后的图片路径"+ imageUrl);
            logUtilssss.e("拍完照后的file内容"+ file.getAbsolutePath().toString().trim());
            ActivityUtil.imagepath(BuyGoldActivity.this, imageUrl, file, ivAddWithHand);
        } else {

        }
    }

}
